from apps.model.serializeModel import model_to_list, model_to_dict
from apps.settingApi.switchCase.serializeParameter import pageResultData, serializeGetFilter, serializeParData
from comm.sqlalchemyConfig import db


# 在线用户列表查询
def getListOnLineModel(model,args):
    # 格式化查询参数
    serializeFilterList, args = serializeGetFilter(model,args)
    # 分页查询数据
    modelDataObj = model.query.filter(*serializeFilterList).order_by(model.id.desc()).paginate(page=args['page'],
                                                                                  per_page=args['pageSize'],
                                                                                  error_out=False)
    # 格式化分页数据
    objData = pageResultData(modelDataObj)
    # 格式化数据列表
    result = model_to_list(modelDataObj, [])
    # 拼接返回的数据
    objData["data"] = result
    return objData

def postListOnLineModel(model,args):
    # 序列化跟校验参数
    addData, err = serializeParData(model=model, argsData=args)
    if err != None:
        return None,err
    if args['off']==1:
        print('进入的是强制下线登录')
        deletedata = db.session.query(model).filter(
            model.user_id == args['user_id']
        ).first()
        db.session.delete(deletedata)
        db.session.commit()
    else:
        print('进入的是普通登录')
        # 判断是否重复登录
        exit_z = db.session.query(model).filter(
            model.lessees_id == args['lessees_id'],
            model.user_id == args['user_id']).first()
        if exit_z != None:
            return True,'用户在线中请勿重新登录'
    result = db.session.query(model).with_for_update().filter_by(id=args['id']).first()
    # 如果数据不存在，则添加新数据
    if result != None:
        db.session.commit()
        return None,'登录失败请刷新重新登录'
    try:
        add = model(**addData)
        db.session.add(add)
        db.session.commit()
        db.session.flush()
        objData = model_to_dict(add, [])
    except Exception as e:
        return None,repr(e)
    return objData,None

